package com.ssb.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.apache.cache.util.Validator;
import com.apache.tools.StrUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;
import java.net.URI;
import java.util.List;
import java.util.Map;

/** description:  http请求工具类
 * @author Hou Dayu 创建时间：2019-07-24  
 */
public class SendHttpUtil {

    private static Logger log = Logger.getLogger("http logs");

    public static JSONObject sendHttp(String url, String method, Map params, Map<String,String> heads) {
        try {
            String str = sendHttpStr(url,method,params,heads,"");
            if(Validator.isNotNull(str)) {
                return JSON.parseObject(str);
            }
        } catch (Exception e) {
            log.error(e);
        }
        return null;
    }

    public static String sendHttpStr(String url, String method, Map params, Map<String,String> heads,String aesKey) {
        String paramStr = "";
        if(params != null){
            paramStr = JSON.toJSONString(params).toString();
        }
        log.info("huanghe request:"+paramStr);
        if(Validator.isNotNull(aesKey)){
            paramStr = AESUtil.encrypt(paramStr,aesKey);
        }
        if(StrUtil.isNotNull(paramStr)){
            return sendHttpMsg(url,method,paramStr,heads);
        }
        return null;
    }

    public static String sendHttpStr(String url, String method, List params, Map<String,String> heads, String aesKey) {
        String paramStr = "";
        if(params != null){
            paramStr = JSON.toJSONString(params).toString();
        }
        log.info("huanghe request:"+paramStr);
        if(Validator.isNotNull(aesKey)){
            paramStr = AESUtil.encrypt(paramStr,aesKey);
        }
        if(StrUtil.isNotNull(paramStr)){
            return sendHttpMsg(url,method,paramStr,heads);
        }
        return null;
    }

    private static String sendHttpMsg(String url, String method, String paramStr,Map<String,String> heads){
        CloseableHttpResponse response = null;
        CloseableHttpClient client = null;
        try {
            //请求超时
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(3000).setSocketTimeout(25000).build();
            if("get".equalsIgnoreCase(method)){
                // 构造请求
                HttpEntityEnclosingRequestBase httpEntity = new HttpEntityEnclosingRequestBase() {
                    @Override
                    public String getMethod() {
                        return "GET";
                    }
                };
                client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
                httpEntity.setURI(URI.create(url));
                httpEntity.setEntity(new StringEntity(paramStr, ContentType.APPLICATION_JSON));
                if (null!=heads && !heads.isEmpty()) {
                    for (Map.Entry<String,String> entry : heads.entrySet()) {
                        httpEntity.setHeader(entry.getKey(), entry.getValue());
                    }
                }
                response = client.execute(httpEntity);
            } else {
                // 构造请求
                HttpPost httpEntity = new HttpPost(url);
                client = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
                httpEntity.setEntity(new StringEntity(paramStr, ContentType.APPLICATION_JSON));
                if (null!=heads && !heads.isEmpty()) {
                    for (Map.Entry<String,String> entry : heads.entrySet()) {
                        httpEntity.setHeader(entry.getKey(), entry.getValue());
                    }
                }
                response = client.execute(httpEntity);
            }
            if (response != null){
                int code = response.getStatusLine().getStatusCode();
                String text = IOUtils.toString(response.getEntity().getContent(),"UTF-8");
                if(code ==200 ) {
                    return text;
                } else {
                    log.warn("url="+url+";请求结果："+code+";"+text);
                }
            } else {
                log.warn("url="+url+";请求结果："+response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(response);
            IOUtils.closeQuietly(client);
        }
        return null;
    }
}
